﻿using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using System.Reflection;
using Spring.Context;
using Spring.Context.Support;

namespace Cn.Edwon.Spring {
    public class BizFactory {
        public static IApplicationContext _context;
        private static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        static BizFactory() {
            log.Debug("初始化BizFactory，读取Spring配置文件");
            _context = ContextRegistry.GetContext();
        }
        public static T Get<T>() {
            try {
                string _name = typeof(T).ToString();
                _name = _name.Substring(_name.LastIndexOf('.') + 1);
                log.Debug("初始化业务类：" + _name);
                return (T)_context.GetObject(_name);
            } catch (Exception ex) {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 基于名称从接口到实体类的反射
        /// 如：IMyBiz获得MyBiz
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        private static T Get_old<T>() {
            string _name = typeof(T).ToString();
            _name = _name.Replace("Port", "Impl");
            _name = _name.Substring(0, _name.LastIndexOf('.') + 1) + _name.Substring(_name.LastIndexOf('.') + 2);
            Type t = Type.GetType(_name, true);
            return (T)Activator.CreateInstance(t);
        }
    }
}
